package it.osg.pipe.sourcegenerators;


import it.osg.pipe.core.SourceGenerator;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

public class MailSourceGenerator extends SourceGenerator {

	public MailSourceGenerator(String modName, String conFilePath) {
		super(modName, conFilePath);
	}

	@Override
	public ArrayList<String> add() {
		ArrayList<String> result = new ArrayList<String>();
		String url = getConfig().get("host") + ":" + getConfig().get("port") + "/" + getConfig().get("solrfolder");
		SolrServer server = new HttpSolrServer(url);
		SolrQuery query = new SolrQuery();
		query.setQuery( "*:*" );
		query.setRows(Integer.valueOf(getConfig().get("maxrow")));
		try {
			QueryResponse rsp = server.query(query);
			SolrDocumentList docs = rsp.getResults();
			Iterator<SolrDocument> iter = docs.iterator();
			while(iter.hasNext()){
				SolrDocument currDoc = iter.next();
				Collection<?> fieldValues = currDoc.getFieldValues(config.get("field"));
				if (fieldValues != null) {
					Iterator<?> iter2 = fieldValues.iterator();
					while(iter2.hasNext()){
						String currContent = (String) iter2.next();
//						byte[] b = currContent.getBytes("UTF-8");
//						String s = new String(b, "UTF-8");
//						result.add(s.toLowerCase());
//						if (s.contains("materialit")){
//							System.out.println(s);
//						}
						result.add(currContent.toLowerCase());
					}
				}
			}
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		System.out.println("\t-> Aggiunti " + result.size() + " token");
		return result;
	
	}


}
